package tcp;

import java.io.*;
import java.net.Inet4Address;
import java.net.Socket;

/**
 * @author Mark
 * @version 1.0
 * @date 2020/5/17 17:39
 * @description 文件上传
 */
public class FileUploadClient {
    public static void main(String[] args) throws Exception {

        // 1.套接字连接
        Socket socket = new Socket(Inet4Address.getByName("127.0.0.1"), 9000);

        // 2.创建一个输出流
        OutputStream outputStream = socket.getOutputStream();

        // 3.读文件
        FileInputStream fileInputStream = new FileInputStream(new File(".") + File.separator + "文件");

        // 4.写文件
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fileInputStream.read(bytes)) != 1) {
            outputStream.write(bytes, 0, length);
        }

        // 通知结束
        socket.shutdownOutput();

        // 确定接收完成
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes1 = new byte[1024];
        int length2;
        while ((length2 = inputStream.read(bytes1)) != 1) {
            byteArrayOutputStream.write(bytes1, 0, length2);
        }

        // 5.关闭流
        byteArrayOutputStream.close();
        inputStream.close();
        fileInputStream.close();
        outputStream.close();
        socket.close();

    }
}
